import path from 'path'
import { app, BrowserWindow, shell } from 'electron'
import MenuBuilder from './menu'

import './api'

let mainWindow: BrowserWindow | null = null

if (process.env.NODE_ENV === 'production') {
  require('source-map-support').install()
}

if (
  process.env.NODE_ENV === 'development' ||
  process.env.DEBUG_PROD === 'true'
) {
  require('electron-debug')()
}

const createWindow = async () => {
  const RESOURCES_PATH = app.isPackaged
    ? path.join(process.resourcesPath, 'assets')
    : path.join(__dirname, '../../assets')

  const CONTENT_URL = app.isPackaged
    ? `file://${__dirname}/ui/index.html`
    : `http://localhost:4201/`

  const getAssetPath = (...paths: string[]): string => {
    return path.join(RESOURCES_PATH, ...paths)
  }

  mainWindow = new BrowserWindow({
    show: false,
    width: 400,
    height: 300,
    icon: getAssetPath('icon.png'),
    webPreferences: {
      nodeIntegration: true,
      // 上下文隔离，如果为true，则需要使用contextBridge暴露API
      // https://www.electronjs.org/docs/tutorial/context-isolation
      contextIsolation: false,
      // preload: __dirname + '/preload.js'
    },
  })

  mainWindow.loadURL(CONTENT_URL)

  mainWindow.webContents.on('did-finish-load', () => {
    if (!mainWindow) {
      throw new Error('"mainWindow" is not defined')
    }
    if (process.env.START_MINIMIZED) {
      mainWindow.minimize()
    } else {
      mainWindow.show()
      mainWindow.focus()
    }
  })

  mainWindow.on('closed', () => {
    mainWindow = null
  })

  const menuBuilder = new MenuBuilder(mainWindow)
  menuBuilder.buildMenu()

  mainWindow.webContents.on('new-window', (event, url) => {
    event.preventDefault()
    shell.openExternal(url)
  })
}

app.on('window-all-closed', () => {
  // Respect the OSX convention of having the application in memory even
  // after all windows have been closed
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.whenReady().then(createWindow).catch(console.log)

app.on('activate', () => {
  if (mainWindow === null) {
    createWindow()
  }
})
